<template>
  <div class="page">
    <!-- 页面按钮点击开通VIP弹窗 -->
    <popup ref="refOpen" @event="$refs.refOpenVip.clearCallback()">
      <open-vip ref="refOpenVip" @event="paySuccess()"></open-vip>
    </popup>

    <breadcrumb>个人中心</breadcrumb>
    <div class="clear"></div>
    <div class="top-bar clear">
      <img :src="userInfo.image | avatarImg(userInfo.gender)">
      <h3>
        <div>
          <b>{{userInfo.name}}</b>
          <div class="gender">
            <i class="icon" :class="userInfo && (userInfo.gender?'icon-nan':'icon-nv')"></i>
          </div>
        </div>
        <div v-show="!userInfo.isSuperUser">
          <div class="endTime">{{endDate}}</div>
        </div>
      </h3>
      <div class="is-super-user" v-show="!userInfo.isSuperUser">
        <button class="button button-assertive-deep button-outline" v-show="canOpenVip"  @click="openVip">开通VIP</button>
        <div class="vip" :class="canOpenVip && 'not'"></div>
      </div>
      <div style="clear"></div>
    </div>
    <div class="center-main">
      <div class="left clear">
        <ul class="clear">
          <li v-for="(item,index) in ['我的信息', '我的关注', '会员中心']" :key="index">
            <span @click="bindTitile(index)" :class="index == active?'active':''">
              {{item}}
            </span>
          </li>
        </ul>
      </div>
      <div class="right">
        <nuxt-child/>
      </div>
    </div>
  </div>
</template>

<script>
import { api } from '@/utils'
import { mapState, mapMutations, mapActions } from 'vuex'
import openVip from '~/components/slot/openVip'
export default {
  components: {
    openVip
  },
  // layout: 'user-center',
  layout: 'zhiyuan-new',
  data () {
    return {
      active: 0,
      infoPopupFlag: false,
      bindPopupFlag: false,
      totalElements: 0,
      currentIndex: 0,
      tabsData: [],
      listData: [],
      provincesData: [],
      cityData: [],
      districtData: [],
      schoolData: [],
      yearData: ['高一', '高二', '高三'],
      bindParams: {
      },
      competeParams: {
      },
      page: 1,
      params: {
        type: 1,
        page: 0,
        size: 10,
        sort: 'desc'
      },
      count: []
    }
  },
  computed: {
    ...mapState({
      userInfo: 'userInfo',
      authInfo: 'authInfo'
    }),
    canOpenVip () {
      const { level, isValid } = this.userInfo
      if (!isValid || !level || level === 'EXPERIENCE') {
        return true
      } else {
        return false
      }
    },
    endDate () {
      // 存在卡并且卡没过期
      const { level, isValid, endDate } = this.userInfo
      let _text = '您还未开通志愿卡'
      if (level && isValid) {
        if (level === 'EXPERIENCE') {
          _text = '体验卡有效期至' + this.format(parseInt(endDate))
        } else {
          _text = '有效期至' + this.format(parseInt(endDate))
        }
      }
      return _text
    }
  },
  methods: {
    ...mapMutations(['SET_AUTH_INFO']),
    ...mapActions(['getUserInfo']),
    bindTitile (index) {
      this.active = index
      let _path = ['/user-center', '/user-center/follow', '/user-center/center']
      this.$router.push({
        path: _path[index]
      })
    },
    // 支付成功后
    paySuccess () {
      this.$refs.refOpen.init(false)
      this.initData()

      let authInfo = this.lodash.cloneDeep(this.authInfo)
      authInfo.isValid = true
      authInfo.level = 'ZHI_YUAN'
      this.SET_AUTH_INFO(authInfo)
      this.getUserInfo(this)
      // setTimeout(() => {
      //   this.$forceUpdate()
      // }, 1000)
      setTimeout(() => {
        location.reload()
      }, 1000)
    },
    // 点击开通VIP
    openVip () {
      this.$refs.refOpen.init() // 打开弹窗
      this.$refs.refOpenVip.init() // 加载VIP数据
    },
    setFavorite (item) {
      this.$axios.get(api.zhiyuanSetFavorite, {
        params: {
          type: this.currentIndex + 1,
          id: item.id
        }
      }).then(data => {
        this.$set(item, 'cancel', !item.cancel)
      })
    },
    filterCityDistrict (arr, id) {
      for (let key in arr) {
        let item = arr[key]
        if (item.id === id) return item
      }
    },
    initData () {
      Promise.all([
        this.$axios.get(api.area),
        this.$axios.get(api.findScholl, {
          params: {
            districtId: this.userInfo.district.id
          }
        })
      ]).then(data => {
        this.provincesData = data[0]
        this.cityData = this.filterCityDistrict(this.provincesData, this.userInfo.province.id).cities
        this.districtData = this.filterCityDistrict(this.cityData, this.userInfo.city.id).districts

        this.schoolData = data[1]._embedded.schools
        this.competeParams = {
          name: this.userInfo.name,
          gender: this.userInfo.gender,
          provinceId: this.userInfo.province.id,
          cityId: this.userInfo.city.id,
          districtId: this.userInfo.district.id,
          school: this.userInfo.school.id,
          startYear: this.userInfo.startYear,
          isStudent: this.userInfo.isStudent
        }
      })
    },
    pagechange (index) {
      this.params.page = index - 1
      this.page = index
      this.getData(this.params)
    },
    getData (params) {
      this.$axios.get(api.favoriteGetAll, {
        params: params
      }).then(data => {
        this.listData = data.list.content
        this.totalElements = data.list.totalElements
        this.count = []
        this.count = [data.collegeNum, data.majorNum, data.careerNum]
        if (this.params.page === 0) {
          this.tabsData = [`关注的大学(${data.collegeNum})`, `关注的专业(${data.majorNum})`, `关注的职业(${data.careerNum})`]
        }
      })
    },
    selectChange (type) {
      if (type === 'province') {
        this.cityData = []
        this.districtData = []
        this.schoolData = []
        this.competeParams.cityId = ''
        this.competeParams.districtId = ''
        this.competeParams.school = ''
        this.competeParams.provinceId && this.$axios.get(`${api.cities}/${this.competeParams.provinceId}/cities`).then(data => {
          this.cityData = data._embedded.cities
        })
      } else if (type === 'city') {
        this.districtData = []
        this.schoolData = []
        this.competeParams.districtId = ''
        this.competeParams.school = ''
        this.competeParams.cityId && (this.districtData = this.filterCityDistrict(this.cityData, this.competeParams.cityId).districts)
      } else if (type === 'district') {
        this.schoolData = []
        this.competeParams.school = ''
        this.competeParams.districtId && this.$axios.get(api.findScholl, {
          params: {
            districtId: this.competeParams.districtId
          }
        }).then(data => {
          this.schoolData = data._embedded.schools
        })
      }
    },
    competeInfo (scope) {
      this.$validator.validateAll(scope).then((result) => {
        if (result) {
          let { school, gender, provinceId, cityId, districtId, startYear, name, isStudent } = this.competeParams
          let params = {
            ...this.userInfo,
            gender: gender,
            name,
            startYear,
            id: this.userInfo.id,
            school: {
              id: school
            },
            // address: {
            province: {
              id: provinceId
            },
            city: {
              id: cityId
            },
            district: {
              id: districtId
            },
            isStudent
            // }
          }
          console.debug(isStudent)
          this.$axios.post(api.updateUserInfo, params).then(data => {
            this.$toasted.success('修改信息成功')
            this.infoPopupFlag = false
            this.getUserInfo(this)
          }).catch(() => {
            this.$toasted.error('接口调用失败')
          })
        }
      })
    },
    tabClick (index) {
      this.currentIndex = index
      this.params.type = index + 1
      this.params.page = 0
      this.page = this.params.page + 1
      if (this.count[index] > 0) {
        this.getData(this.params)
      } else {
        this.listData = []
      }
    },
    bindCard (scope) {
      this.$validator.validateAll(scope).then((result) => {
        if (result) {
          let authInfo = this.authInfo
          this.$axios.post(api.bindingCard, {
            ...this.bindParams,
            phoneNumber: authInfo.phoneNum
          }).then(data => {
            let authInfo = this.lodash.cloneDeep(this.authInfo)
            authInfo.isValid = true
            authInfo.level = data.level
            this.SET_AUTH_INFO(authInfo)
            this.getUserInfo(this)
            this.bindPopupFlag = false
          }).catch(err => {
            this.$toasted.error(err.data.message)
          })
        }
      })
    },
    close () {
      this.infoPopupFlag = !this.infoPopupFlag
      this.initData()
      console.log(this.competeParams)
    },
    nowSub () {
      let _path = this.$nuxt.$route.name
      if (_path === 'user-center') this.active = 0
      if (_path === 'user-center-follow') this.active = 1
      if (_path === 'user-center-center') this.active = 2
    },
    add0 (m) { return m < 10 ? '0' + m : m },
    format (shijianchuo) {
      var time = new Date(shijianchuo)
      var y = time.getFullYear()
      var m = time.getMonth() + 1
      var d = time.getDate()
      return y + '-' + this.add0(m) + '-' + this.add0(d)
    }
  },
  mounted () {
    /* for (let i = 0; i < 4; i++) {
      this.yearData[i] = formatDate(new Date(), 'yyyy') - i
    } */
    this.nowSub()
    this.initData()
    this.getData(this.params)
    console.log('userInfo', this.userInfo)
    // this.userInfo.endDate && (this.endDate = this.format(parseInt(this.userInfo.endDate)))
  }
}
</script>

<style scoped lang="scss">
// .page-bg{
//   position: relative;
//   &::after{
//     content:""; display:block;
//     position:absolute; left:-10px; top:-10px;
//     z-index:1;
//     width:1320px; height:105%;
//     background:#FAFAFA;
//   }
// }

.page {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.top-bar {
  display: flex;
  position: relative; z-index:2;
  height:136px;
  border-radius:10px;
  background:$light;
  margin-bottom:15px;
  align-items:center;
  padding-left:25px;
  .endTime{
    color:$pink;
    font-size:14px;
    padding-top:10px;
  }
  .gender{
    padding-left:10px;
    display: inline-block;
    height:26px; line-height:26px;
    font-weight:bold;
    .icon-nan{
      color:$table-b;
    }
    .icon-nv{
      color:#FF5089;
    }
  }
  .is-super-user{
    position:absolute; top:0px; right:0px; z-index:1;
    height:100%; width:300px;
  }
  .vip{
    position:absolute; top:20px; right:20px; z-index:1;
    background:url('/images/zhiyuan/shape.png') no-repeat center center;
    background-size: cover;
    width:258px; height:100px;
    &.not{
      background:url('/images/zhiyuan/not.png') no-repeat center center;
    }
  }
  .button {
    position: absolute;
    right: 24px;
    top: 50%; z-index:3;
    transform: translateY(-50%);
    border:none; padding:0px;
    height: 32px; line-height:32px;
    width: 82px; text-align: center;
    background: $pink;
    border-radius: 20px;
    font-size:16px;
    color:$light;
    cursor: pointer;
  }
  h3 {
    font-weight:normal;
    font-size: 18px;
    display: flex;
    margin-left:10px;
    // align-items: center;
    justify-content: center;
    flex-direction: column;
    span {
      background: $assertive-deep;
      color: $light;
      font-weight: normal;
      padding: 2px 8px;
      border-radius: 6px;
      font-size: 12px;
      margin-left: 5px;
      position: relative;
      display: block;
      margin-top: -3px;
      &:after {
        content: "";
        width: 0;
        height: 0;
        border-width: 4px 4px 0;
        border-style: solid;
        border-color: $assertive-deep transparent transparent; /*灰 透明 透明 */
        position: absolute;
        bottom: -4px;
        left: 50%;
        margin-left: -4px;
      }
    }
  }
  img {
    display: block;
    width: 96px;
    height: 96px;
    border-radius: 50%;
    border: 1px solid $grey;
  }
}
.center-main {
  position: relative; z-index:2;
  display: flex;
  justify-content: space-between;
  flex: 1;
  // overflow: hidden;
  .left {
    width: 280px;
    min-height:300px;
    background: $light;
    border-radius:10px;
    padding: 10px 20px;
    >ul{
      padding:10px 0;
      li{
        text-align:center;
        padding:10px 0;
        span{
          cursor:pointer;
          height:33px;
          line-height:33px;
          position:relative;
          color:#ADADAD;
          font-size:24px;
          display:inline-block;
          // padding-left:25px;
          &.active{
            color:#444;
            &:after{
              content:"●";
              position:absolute;
              left:-25px; top:0px;
            }
          }
        }
      }
    }
  }
  .right {
    width:1025px;
    background:$light;
    border-radius:10px;
    // overflow: hidden;
    display: flex;
    // padding: 20px 36px;
    flex-direction: column;
    /deep/ .tab {
      margin: 0 0 30px;
      .triped {
        background: $royal-deep;
      }
      > span {
        padding-right: 40px;
      }
    }
  }
  .tabs-wrap {
    flex: 1;
    overflow: auto;
    .box {
      .item {
        padding-left: 12px;
      }
    }
  }
}
</style>
